<template>
	<view class="order-page">
		<!-- 顶部标签栏 -->
		<view class="tab-bar">
			<text v-for="tab in tabs" :key="tab.value" :class="{ active: currentTab === tab.value }"
				@click="changeTab(tab.value)">
				{{ tab.label }}
			</text>
		</view>

		<!-- 订单列表 -->
		<view class="orders">
			<view v-for="(order, idx) in filteredOrders" :key="order.id || idx" class="order-card">
				<view class="order-header">
					<text>订单号：{{ (order.shopOrder && order.shopOrder.orderNo) || order.orderNo || order.id }}</text>
					<text style="margin-left: 12px">状态：{{ getStatusText(order.statusText) }}</text>
					<text v-if="order.remainingTime" style="margin-left:12px">
						倒计时：{{ formatRemainingTime(order.remainingTime) }}
					</text>
				</view>

				<!-- 商品列表 -->
				<view class="order-items" @click="navigateToOrderPage(order)">
					<view v-for="(it, i) in order.items" :key="it.id || i" class="item-row">
						<image :src="(it.sku && it.sku.imageUrl) || it.imageUrl" class="thumb" />
						<view class="prod-info">
							<text class="prod-name">{{ it.productName }}</text>
							<text class="prod-spec">{{ (it.specInfo).replace(/[{}]/g, '') }}</text>
							<text class="prod-price">¥{{ it.price }} × {{ it.quantity }}</text>
						</view>
					</view>
				</view>

				<!-- 订单总价 -->
				<view class="order-total">
					<text>共 {{ order.items.length }} 样商品</text>
					<text>合计：¥{{ order.totalAmount }}</text>
				</view>

				<!-- 操作按钮 -->
				<view class="order-actions">
					<!-- 待付款 -->
					<button v-if="order.statusText === 'pendingPayment'" @click="onCancelOrder(order)">取消订单</button>
					<button v-if="order.statusText === 'pendingPayment'" @click="onPay(order)">立即支付</button>

					<!-- 待发货 -->
					<button v-if="order.statusText === 'pendingShipping'" @click="onCancelOrder(order)">取消订单</button>
					<button v-if="order.statusText === 'pendingShipping'" @click="onBuyAgain(order)">再次购买</button>

					<!-- 待收货 -->
					<button v-if="order.statusText === 'pendingReceipt'" @click="onViewLogistics(order)">查看物流</button>
					<button v-if="order.statusText === 'pendingReceipt'" @click="onBuyAgain(order)">再次购买</button>
					<button v-if="order.statusText === 'pendingReceipt'" @click="onConfirmReceipt(order)">确认收货</button>

					<!-- 待评价 -->
					<button
						v-if="order.statusText === 'pendingReview' || order.statusText === 'pendingComplete' || order.statusText === 'pendingCancle'  "
						@click="onBuyAgain(order)">再次购买</button>
					<button v-if="order.statusText === 'pendingReview'" @click="onReturnExchange(order)">退换货</button>
					<button v-if="order.statusText === 'pendingReview'" @click="onReviewReward(order)">评价有礼</button>
				</view>
				
				<!-- 支付密码输入弹窗 -->
				<view v-if="showPasswordModal" class="password-modal-mask" @click="closePasswordModal">
					<view class="password-modal-popup" @click.stop>
						<view class="password-modal-header">
							<text class="password-modal-title">请输入支付密码</text>
							<text class="close-btn" @click="closePasswordModal">×</text>
						</view>
						<view class="password-modal-content">
							<text class="payment-amount">支付金额：¥{{ currentOrder.totalAmount }}</text>
							<view class="password-input-container">
								<input 
									class="password-input" 
									type="number" 
									password 
									maxlength="6" 
									placeholder="密码6个1"
									:value="password"
									@input="onPasswordInput"
									focus
								/>
							</view>
							<view class="password-dots">
								<view 
									class="password-dot" 
									v-for="i in 6" 
									:key="i"
									:class="{ 'filled': i <= password.length }"
								></view>
							</view>
						</view>
						<view class="password-modal-footer">
							<view class="cancel-btn" @click="closePasswordModal">
								<text class="cancel-text">取消</text>
							</view>
							<view class="confirm-btn" @click="confirmPayment">
								<text class="confirm-text">确认支付</text>
							</view>
						</view>
					</view>
				</view>
				
			</view>

			<view v-if="filteredOrders.length === 0" class="empty">
				<text>暂无订单</text>
			</view>
		</view>
	</view>
</template>

<script>
	import {
		get,put
	} from '@/utils/request';
	import {
		jwtDecode
	} from 'jwt-decode';

	export default {
		data() {
			return {
				tabs: [{
						label: '全部',
						value: 'all'
					},
					{
						label: '待付款',
						value: 'pendingPayment'
					},
					{
						label: '待发货',
						value: 'pendingShipping'
					},
					{
						label: '待收货',
						value: 'pendingReceipt'
					},
					{
						label: '待评价',
						value: 'pendingReview'
					}
				],
				currentTab: 'all',
				list: [],
				orders: [],
				pageNum: 1,
				pageSize: 1000,
				timers: {},
				currentOrder: null,
				showPasswordModal: false,
				password: ''
			};
		},

		computed: {
			filteredOrders() {
				if (this.currentTab === 'all') return this.orders;
				return this.orders.filter(order => order.statusText === this.currentTab);
			}
		},

		methods: {
			goToUnpaidOrder(orderData) {
				uni.setStorageSync("unpaidOrderData", orderData);
				uni.navigateTo({
					url: "/pages/unpaidorder/unpaidorder"
				});
			},
			goToShipOrder(orderData) {
				uni.setStorageSync("shipOrderData", orderData);
				uni.navigateTo({
					url: "/pages/shiporder/shiporder"
				});
			},
			goToReceiveOrder(orderData) {
				uni.setStorageSync("receiveOrderData", orderData);
				uni.navigateTo({
					url: "/pages/receiveorder/receiveorder"
				});
			},
			goToReviewOrder(orderData) {
				uni.setStorageSync("reviewOrderData", orderData);
				uni.navigateTo({
					url: "/pages/revieworder/revieworder"
				});
			},
			goToCompleteOrder(orderData) {
				uni.setStorageSync("completeOrderData", orderData);
				uni.navigateTo({
					url: "/pages/orderComplete/orderComplete"
				});
			},
			goToCancleOrder(orderData) {
				uni.setStorageSync("cancleOrderData", orderData);
				uni.navigateTo({
					url: "/pages/orderCancle/orderCancle"
				});
			},

			navigateToOrderPage(order) {
				const status = order.statusText; // 假设你传过来的订单里有 statusText 字段

				if (status === "pendingPayment") {
					this.goToUnpaidOrder(order);
					console.log("去往未付款页面");
					console.log(order);
				} else if (status === "pendingShipping") {
					this.goToShipOrder(order);
					console.log("去往待发货页面");
					console.log(order);
				} else if (status === "pendingReceipt") {
					this.goToReceiveOrder(order);
					console.log("去往待收货页面");
					console.log(order);
				} else if (status === "pendingReview") {
					this.goToReviewOrder(order);
					console.log("去往待评价页面", order);
				} else if (status === "pendingComplete") {
					this.goToCompleteOrder(order);
					console.log("去往已完成页面", order);
				} else if (status === "pendingCancle") {
					this.goToCancleOrder(order);
					console.log("去往已取消页面", order);
				} else {
					console.log("未匹配到状态，跳转失败", order);
				}
			},




			getStatusText(status) {
				const statusMap = {
					'pendingPayment': '待付款',
					'pendingShipping': '待发货',
					'pendingReceipt': '待收货',
					'pendingReview': '待评价',
					'pendingCancle': '已取消',
					'pendingRefund': '已退款',
					'pendingComplete': '已完成',
				};
				return statusMap[status] || status;
			},

			changeTab(tab) {
				this.currentTab = tab;
			},

			calculateOrderTotal(items) {
				return items.reduce((total, item) => {
					return total + (item.price * item.quantity);
				}, 0).toFixed(2);
			},

			getData() {
				const token = uni.getStorageSync('token');
				let userId = null;

				if (token) {
					try {
						const decoded = jwtDecode(token);
						userId = decoded.user_id || decoded.userId || decoded.id;
					} catch (e) {
						console.error('Token 解析失败', e);
					}
				}

				if (!userId) {
					uni.showToast({
						title: '用户信息无效，请重新登录',
						icon: 'none'
					});
					return;
				}

				get('/transaction/shoporderitem/list', {
						pageNum: this.pageNum,
						pageSize: this.pageSize,
						membersId: userId,
					})
					.then((res) => {
						if (res.code === 200 && Array.isArray(res.rows)) {
							this.list = res.rows.map((item) => ({
								...item,
								selected: false,
								quantity: 1,
							}));
						} else {
							uni.showToast({
								title: '数据加载失败',
								icon: 'none',
							});
						}
					})
					.catch((err) => {
						console.error('getData 请求失败', err);
						uni.showToast({
							title: '请求失败',
							icon: 'none'
						});
					});
			},

			async fetchOrders() {
				const token = uni.getStorageSync('token');
				let userId = null;

				if (token) {
					try {
						const decoded = jwtDecode(token);
						userId = decoded.user_id || decoded.userId || decoded.id;
					} catch (e) {
						console.error('Token 解析失败', e);
					}
				}

				if (!userId) {
					uni.showToast({
						title: '用户信息无效，请重新登录',
						icon: 'none'
					});
					return;
				}

				try {
					const orderRes = await get('/transaction/shoporder/list', {
						pageNum: this.pageNum,
						pageSize: this.pageSize,
						membersId: userId,
					});

					if (!(orderRes && orderRes.code === 200 && Array.isArray(orderRes.rows))) {
						uni.showToast({
							title: '订单数据加载失败',
							icon: 'none'
						});
						return;
					}

					const mainOrders = orderRes.rows;
					const ordersWithItems = [];

					for (const main of mainOrders) {
						const orderId = main.id ?? main.shopOrder?.id ?? main.orderId;
						if (!orderId) continue;

						const itemsRes = await get('/transaction/shoporderitem/list', {
							orderId,
						});

						const items = itemsRes && itemsRes.code === 200 && Array.isArray(itemsRes.rows) ? itemsRes
							.rows : [];
						const numericStatus = main.shopOrder?.status ?? main.status ?? main.orderStatus ?? null;
						const statusKey = this.mapStatusToKey(numericStatus);

						const mappedItems = items.map((it) => {
							const copy = {
								...it
							};
							copy.orderId = orderId;
							copy.status = copy.status ?? numericStatus;
							copy.statusText = this.mapStatusToKey(copy.status);

							if (copy.statusText === 'pendingPayment' && !copy.remainingTime) {
								copy.remainingTime = 30 * 60;
							}
							return copy;
						});

						mappedItems.forEach((it) => {
							if (it.remainingTime && it.statusText === 'pendingPayment') {
								this.startCountdown(it);
							}
						});

						ordersWithItems.push({
							...main,
							id: orderId,
							status: numericStatus,
							statusText: statusKey,
							items: mappedItems,
						});
					}

					this.orders = ordersWithItems;
				} catch (err) {
					console.error('fetchOrders 失败', err);
					uni.showToast({
						title: '请求失败',
						icon: 'none'
					});
				}
			},

			mapStatusToKey(status) {
				const map = {
					0: 'pendingPayment',
					1: 'pendingShipping',
					2: 'pendingReceipt',
					3: 'pendingReview',
					4: 'pendingCancle',
					5: 'pendingRefund',
					6: 'pendingComplete',

				};

				if (typeof status === 'string') {
					if (['pendingPayment', 'pendingShipping', 'pendingReceipt', 'pendingReview'].includes(status)) {
						return status;
					}
					const cnMap = {
						'待付款': 'pendingPayment',
						'待发货': 'pendingShipping',
						'待收货': 'pendingReceipt',
						'待评价': 'pendingReview',
					};
					if (cnMap[status]) return cnMap[status];

					const n = Number(status);
					if (!Number.isNaN(n) && map[n]) return map[n];
				}

				if (typeof status === 'number' && map[status]) return map[status];
				return status;
			},

			startCountdown(item) {
				if (!item) return;
				const key = `timer_${item.orderId}_${item.id ?? item.skuId ?? Math.random()}`;

				if (this.timers[key]) {
					clearInterval(this.timers[key]);
				}

				item.remainingTime = Number(item.remainingTime) || 0;

				this.timers[key] = setInterval(() => {
					if (item.remainingTime <= 0) {
						clearInterval(this.timers[key]);
						delete this.timers[key];
						item.remainingTime = 0;
					} else {
						item.remainingTime -= 1;
					}
				}, 1000);
			},

			clearAllTimers() {
				Object.keys(this.timers).forEach((k) => {
					try {
						clearInterval(this.timers[k]);
					} catch (e) {
						// ignore
					}
					delete this.timers[k];
				});
			},

			formatRemainingTime(sec) {
				const s = Number(sec) || 0;
				const h = Math.floor(s / 3600).toString().padStart(2, '0');
				const m = Math.floor((s % 3600) / 60).toString().padStart(2, '0');
				const ss = Math.floor(s % 60).toString().padStart(2, '0');
				return `${h}:${m}:${ss}`;
			},


			async onCancelOrder(order) {
			  uni.showModal({
			    title: '确认取消',
			    content: '您确定要取消订单吗？',
			    success: async (res) => {
			      if (res.confirm) {
			        try {
			          // 拷贝一份订单对象并修改状态
			          const payload = { ...order, status: 4 };
			
			          const response = await put('/transaction/shoporder', payload);
			
			          if (response.code === 200) {
			
			            uni.showToast({
			              title: '取消成功',
			              icon: 'success'
			            });
			          } else {
			            uni.showToast({
			              title: '操作失败',
			              icon: 'none'
			            });
			          }
			        } catch (err) {
			          uni.showToast({
			            title: '请求失败',
			            icon: 'none'
			          });
			        }
			      }
			    }
			  });
			},


			onPay(order) {
				console.log('支付订单', order);
				uni.showModal({
					title: '确认支付',
					content: '您确定要支付订单吗？',
					success: (res) => {
						if (res.confirm) {
							uni.showToast({
								title: '前往支付',
								icon: 'success'
							});
							this.currentOrder = order;
							this.showPasswordModal = true;
							console.log(order.totalAmount)
						}
					}
				});
			},
			
			// 关闭密码输入弹窗
			closePasswordModal() {
				this.showPasswordModal = false;
				this.password = '';
			},
			
			// 输入密码
			onPasswordInput(e) {
				this.password = e.detail.value;
			},
			
			// 确认支付
			// 确认支付
			async confirmPayment() {
			  if (!this.password || this.password.length !== 6) {
			    uni.showToast({
			      title: '请输入6位支付密码',
			      icon: 'none'
			    });
			    return;
			  }
			
			  // 检查密码是否正确（固定密码为111111）
			  if (this.password !== '111111') {
			    uni.showLoading({ title: '支付中...' });
			    setTimeout(() => {
			      uni.hideLoading();
			      uni.navigateTo({ url: '/pages/PayFail/PayFail' });
			    }, 2000);
			    return;
			  }
			
			  uni.showLoading({ title: '支付中...' });
			
			  try {
			    // 直接修改订单状态
				
			    const payload = { ...this.currentOrder, status: 1 }; // 0 → 1
			    const res = await put('/transaction/shoporder', payload);
			
			    uni.hideLoading();
			
			    if (res.code === 200) {
			      uni.navigateTo({ url: '/pages/PaySuccess/PaySuccess' });
			    } else {
			      uni.showToast({
			        title: '支付失败',
			        icon: 'none'
			      });
			    }
			  } catch (err) {
			    uni.hideLoading();
			    uni.showToast({
			      title: '请求失败',
			      icon: 'none'
			    });
			  }
			},

			onBuyAgain(order) {
				console.log('再次购买', order);
				uni.navigateTo({
					url: '/pages/cart/noTabBarCart'
				});
			},

			onViewLogistics(order) {
				console.log('查看物流', order);
				uni.navigateTo({
					url: `/pages/delivery/delivery?orderId=${order.id}`
				});
			},

			async onConfirmReceipt(order) {
			  uni.showModal({
			    title: '确认收货',
			    content: '您确定已收到货物吗？',
			    success: async (res) => {
			      if (res.confirm) {
			        try {
						console.log(order);
			          const payload = { ...order, status: 3 };
			          const response = await put('/transaction/shoporder', payload);
			
			          if (response.code === 200) {
			            uni.showToast({
			              title: '收货成功',
			              icon: 'success'
			            });
			            // 刷新订单
			          } else {
			            uni.showToast({
			              title: '操作失败',
			              icon: 'none'
			            });
			          }
			        } catch (err) {
			          uni.showToast({
			            title: '请求失败',
			            icon: 'none'
			          });
			        }
			      }
			    }
			  });
			},
			





			onReturnExchange(order) {
				console.log('退换货', order);
				uni.navigateTo({
					url: `/pages/yzmaftersale/yzmaftersale?orderId=${order.id}`
				});
			},

			onReviewReward(order) {
				console.log('评价有礼', order);
				uni.navigateTo({
					url: `/pages/review/review?orderId=${order.id}`
				});
			},
		},

		onShow() {
			this.getData();
			this.fetchOrders();
		},

		onUnload() {
			this.clearAllTimers();
		},
	};
</script>

<style scoped>
	.order-page {
		padding: 12px;
		background-color: #f5f5f5;
	}

	.tab-bar {
		display: flex;
		justify-content: space-around;
		padding: 10px 0;
		background-color: #fff;
		margin-bottom: 10px;
		border-bottom: 1px solid #eee;
	}

	.tab-bar text {
		padding: 5px 0;
		color: #666;
	}

	.tab-bar .active {
		color: orange;
		border-bottom: 2px solid orange;
	}

	.orders {
		margin-top: 10px;
	}

	.order-card {
		border: 1px solid #eee;
		border-radius: 6px;
		margin-bottom: 12px;
		padding: 12px;
		background: #fff;
	}

	.order-header {
		display: flex;
		align-items: center;
		margin-bottom: 8px;
		font-size: 14px;
		color: #666;
	}

	.order-items {
		margin-bottom: 8px;
	}

	.item-row {
		display: flex;
		align-items: center;
		padding: 8px 0;
		border-top: 1px solid #f2f2f2;
	}

	.item-row:first-child {
		border-top: none;
	}

	.thumb {
		width: 64px;
		height: 64px;
		border-radius: 4px;
		margin-right: 12px;
	}

	.prod-info {
		flex: 1;
		display: flex;
		flex-direction: column;
	}

	.prod-name {
		font-size: 14px;
		margin-bottom: 4px;
	}

	.prod-spec {
		font-size: 12px;
		color: #999;
		margin-bottom: 4px;
	}

	.prod-price {
		font-size: 14px;
		color: #f40;
	}

	.order-total {
		display: flex;
		justify-content: flex-end;
		padding: 8px 0;
		border-top: 1px solid #f2f2f2;
		font-size: 14px;
	}

	.order-total text:last-child {
		margin-left: 10px;
		color: #f40;
		font-weight: bold;
	}

	.order-actions {
		display: flex;
		justify-content: flex-end;
		padding-top: 8px;
		border-top: 1px solid #f2f2f2;
	}

	.order-actions>button {
		margin-left: 8px;
		padding: 4px 8px;
		font-size: 12px;
		border-radius: 3px;
		border: 1px solid #ddd;
		background: #fff;
	}

	.order-actions>button:last-child {
		background: orange;
		color: #fff;
		border-color: orange;
	}

	.empty {
		text-align: center;
		color: #888;
		padding: 24px 0;
	}
	/* 支付密码输入弹窗样式 */
	.password-modal-mask {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background-color: rgba(0, 0, 0, 0.1);
		z-index: 99999;
		display: flex;
		align-items: center;
		justify-content: center;
	}
	
	.password-modal-popup {
		width: 600rpx;
		background-color: #fff;
		border-radius: 20rpx;
		overflow: hidden;
		animation: slideUp 0.3s ease-out;
	}
	
	.password-modal-header {
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 30rpx;
		border-bottom: 1rpx solid #eee;
	}
	
	.password-modal-title {
		font-size: 32rpx;
		font-weight: bold;
		color: #333;
	}
	
	.password-modal-content {
		padding: 40rpx 30rpx;
		text-align: center;
	}
	
	.payment-amount {
		display: block;
		font-size: 28rpx;
		color: #666;
		margin-bottom: 30rpx;
	}
	
	.password-input-container {
		margin-bottom: 30rpx;
	}
	
	.password-input {
		width: 100%;
		height: 80rpx;
		border: 2rpx solid #ddd;
		border-radius: 10rpx;
		padding: 0 20rpx;
		font-size: 32rpx;
		text-align: center;
		letter-spacing: 10rpx;
	}
	
	.password-dots {
		display: flex;
		justify-content: center;
		gap: 20rpx;
		margin-bottom: 30rpx;
	}
	
	.password-dot {
		width: 20rpx;
		height: 20rpx;
		border-radius: 50%;
		border: 2rpx solid #ddd;
		background-color: transparent;
	}
	
	.password-dot.filled {
		background-color: #333;
		border-color: #333;
	}
	
	.password-modal-footer {
		display: flex;
		border-top: 1rpx solid #eee;
	}
	
	.password-modal-footer .cancel-btn {
		flex: 1;
		height: 100rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		background-color: #f5f5f5;
	}
	
	.cancel-text {
		font-size: 32rpx;
		color: #666;
	}
	
	.password-modal-footer .confirm-btn {
		flex: 1;
		height: 100rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		background-color: #ff2a3a;
	}
	/* 动画效果 */
	@keyframes slideUp {
		from {
			transform: translateY(100%);
			opacity: 0;
		}
		to {
			transform: translateY(0);
			opacity: 1;
		}
	}
</style>